import { ref, reactive } from 'vue';
import type { MessageOptions } from '@/components/BaseMessage.vue';

// 消息状态管理
export const messageState = reactive({
  visible: false,
  options: {
    message: '',
    type: 'info' as 'success' | 'error' | 'warning' | 'info',
    timeout: 4000,
    location: 'top',
    multiLine: false,
    vertical: false
  } as MessageOptions
});

// 消息队列
const messageQueue = ref<MessageOptions[]>([]);
let isProcessing = false;

/**
 * 显示消息
 */
export function showMessage(message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info', options?: Partial<MessageOptions>) {
  const messageOptions: MessageOptions = {
    message,
    type,
    timeout: 4000,
    location: 'top',
    multiLine: false,
    vertical: false,
    ...options
  };

  // 如果当前有消息在显示，加入队列
  if (messageState.visible || isProcessing) {
    messageQueue.value.push(messageOptions);
    return;
  }

  // 直接显示消息
  displayMessage(messageOptions);
}

/**
 * 显示消息的内部方法
 */
function displayMessage(options: MessageOptions) {
  isProcessing = true;
  messageState.options = { ...options };
  messageState.visible = true;

  // 设置自动关闭
  if (options.timeout && options.timeout > 0) {
    setTimeout(() => {
      closeMessage();
    }, options.timeout);
  }
}

/**
 * 关闭当前消息
 */
export function closeMessage() {
  messageState.visible = false;
  isProcessing = false;

  // 处理队列中的下一个消息
  setTimeout(() => {
    if (messageQueue.value.length > 0) {
      const nextMessage = messageQueue.value.shift();
      if (nextMessage) {
        displayMessage(nextMessage);
      }
    }
  }, 300); // 给一点延迟，让动画完成
}

/**
 * 清空消息队列
 */
export function clearMessageQueue() {
  messageQueue.value = [];
}

/**
 * 基础消息方法 - 兼容原有的 $baseMessage 调用方式
 */
export function baseMessage(message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info', options?: Partial<MessageOptions>) {
  showMessage(message, type, options);
}

// 快捷方法
export const message = {
  success: (msg: string, options?: Partial<MessageOptions>) => showMessage(msg, 'success', options),
  error: (msg: string, options?: Partial<MessageOptions>) => showMessage(msg, 'error', options),
  warning: (msg: string, options?: Partial<MessageOptions>) => showMessage(msg, 'warning', options),
  info: (msg: string, options?: Partial<MessageOptions>) => showMessage(msg, 'info', options)
};

export default {
  showMessage,
  closeMessage,
  clearMessageQueue,
  baseMessage,
  message,
  messageState
}; 